import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { Creative, Promotion } from '@/core/interfaces/promotion'

export enum OrderOperateEnum {
  normal,
  editable
}

export enum isFirstEnum {
  NotAdded,
  First,
  Other
}

export const usePromotionStore = defineStore('Promotion', () => {
  const currentPromotionData = ref<Partial<Promotion>>({})
  const orderDetailOperate = ref<OrderOperateEnum>(OrderOperateEnum.normal)
  const creatives = ref<Creative[]>([])
  const currentOrderWordId = ref<Creative['orderWordId'] | undefined>()
  const currentCreative = computed<Partial<Creative>>(() => {
    return creatives.value.find((item) => item.orderWordId === currentOrderWordId.value) || {}
  })

  const isFirstCreative = computed<Partial<Creative>>(() => {
    return (
      creatives.value.find(
        (item) => item.isFirst === isFirstEnum.First && (item.clientType === 0 || item.clientType === 2)
      ) || {}
    )
  })
  const isWapFirstCreative = computed<Partial<Creative>>(() => {
    return (
      creatives.value.find(
        (item) => item.isFirst === isFirstEnum.First && (item.clientType === 1 || item.clientType === 2)
      ) || {}
    )
  })

  const creativesExceptCurrent = computed(() => {
    return creatives.value.filter((item) => item.orderWordId !== currentCreative.value?.orderWordId)
  })

  function setCurrentPromotionData(promotion: Promotion) {
    currentPromotionData.value = promotion
  }

  function setOrderDetailOperate(operate: OrderOperateEnum) {
    orderDetailOperate.value = operate
  }

  function setCreatives(data: Creative[]) {
    data.forEach((creative) => {
      if (creative.pcGoods?.length > 0) {
        creative.pcGoods.forEach((item) => {
          item.pictureURL = `${import.meta.env.VITE_UPLOAD_URL}${item.pictureURL}`
        })
      }
      if (creative.wapGoods?.length > 0) {
        creative.wapGoods.forEach((item) => {
          item.pictureURL = `${import.meta.env.VITE_UPLOAD_URL}${item.pictureURL}`
        })
      }
    })
    creatives.value = data
  }

  function setCurrentOrderWordId(id: Creative['id']) {
    currentOrderWordId.value = id
  }

  return {
    currentOrderWordId,
    currentPromotionData,
    currentCreative,
    orderDetailOperate,
    creatives,
    creativesExceptCurrent,
    isFirstCreative,
    isWapFirstCreative,
    setCurrentPromotionData,
    setOrderDetailOperate,
    setCurrentOrderWordId,
    setCreatives
  }
})
